package com.lzc.jobrecomendbackend.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.lzc.jobrecomendbackend.config.LLMConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 大语言模型服务
 */
@Service
public class LLMService {

    @Autowired
    private LLMConfig llmConfig;

    @Autowired
    private RestTemplate restTemplate;

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 发送请求到大模型
     *
     * @param prompt 提示词
     * @return 模型响应文本
     */
    public String sendPrompt(String prompt) {
        try {
            String url = llmConfig.getBaseUrl() + "/chat/completions";
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(llmConfig.getApiKey());
            
            // 构建请求体
            ObjectNode requestBody = objectMapper.createObjectNode();
            requestBody.put("model", llmConfig.getModelName());
            requestBody.put("enable_thinking", false); // 必需参数，非流式调用设为false
            
            // 设置最大token数量
            requestBody.put("max_tokens", 1000);
            
            ArrayNode messagesArray = requestBody.putArray("messages");
            
            // 系统消息
            ObjectNode systemMessage = objectMapper.createObjectNode();
            systemMessage.put("role", "system");
            systemMessage.put("content", "你是职业规划顾问，提供专业、实用的技术职业建议，内容精炼但要保留重要细节。");
            messagesArray.add(systemMessage);
            
            // 用户消息
            ObjectNode userMessage = objectMapper.createObjectNode();
            userMessage.put("role", "user");
            userMessage.put("content", prompt);
            messagesArray.add(userMessage);
            
            // 记录API请求
            System.out.println("========== 大模型API请求 ==========");
            System.out.println("请求模型: " + llmConfig.getModelName());
            
            // 发送请求
            HttpEntity<String> entity = new HttpEntity<>(requestBody.toString(), headers);
            System.out.println("正在调用大模型API...");
            String response = restTemplate.postForObject(url, entity, String.class);
            
            // 记录API响应摘要
            System.out.println("========== 大模型API响应 ==========");
            System.out.println("响应长度: " + response.length() + " 字符");
            
            // 解析响应
            JsonNode responseJson = objectMapper.readTree(response);
            String content = extractContentFromResponse(responseJson);
            
            // 记录提取到的内容长度
            System.out.println("提取内容长度: " + content.length() + " 字符");
            
            return content;
        } catch (Exception e) {
            // 记录错误信息
            System.err.println("========== 大模型API错误 ==========");
            System.err.println("错误信息: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("调用大模型API失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 从响应中提取内容
     *
     * @param responseJson 响应JSON
     * @return 提取的内容
     */
    private String extractContentFromResponse(JsonNode responseJson) {
        try {
            // 优先从choices.message.content中提取
            JsonNode choicesNode = responseJson.path("choices");
            if (choicesNode.isArray() && choicesNode.size() > 0) {
                System.out.println("使用choices.message.content格式解析");
                JsonNode firstChoice = choicesNode.get(0);
                JsonNode messageNode = firstChoice.path("message");
                if (!messageNode.isMissingNode()) {
                    return messageNode.path("content").asText();
                }
            }
            
            // 尝试从output.text中提取
            JsonNode outputNode = responseJson.path("output");
            if (!outputNode.isMissingNode()) {
                System.out.println("使用output.text格式解析");
                JsonNode textNode = outputNode.path("text");
                if (!textNode.isMissingNode()) {
                    return textNode.asText();
                }
            }
            
            System.err.println("无法从响应中提取内容");
            throw new RuntimeException("无法解析AI响应: " + responseJson.toString());
        } catch (Exception e) {
            System.err.println("解析响应出错: " + e.getMessage());
            throw new RuntimeException("解析AI响应失败: " + e.getMessage(), e);
        }
    }
} 